package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 聪哥
 * @since 2024-09-18
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    /**
     * 关注或取关
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {

        // 1. 取出当前登录的用户id 作为关注者的id
        Long userId = UserHolder.getUser().getId();

        // 2. 判断isFollow的值，判断实现关注 还是 取关
        if(BooleanUtil.isTrue(isFollow)){
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            follow.setCreateTime(LocalDateTime.now());
            // 3. 关注用户，则将followUserId 和 userid 添加到 tb_follow表中
            boolean isSuccess = save(follow);
            if(isSuccess){
                // 把关注用户信息存入Redis的set集合中
                stringRedisTemplate.opsForSet().add(RedisConstants.FOLLOWER_KEY + userId , followUserId.toString());
            }
        }else{
            // 4. 取关用户，则将followUserId 和 userid 从 tb_follow表中删除
            boolean isSuccess =  remove(new QueryWrapper<Follow>()
                                    .eq("user_id" ,userId)
                                    .eq("follow_user_id",followUserId));
            if(isSuccess){
                // 把关注用户信息从Redis的set集合中移除
                stringRedisTemplate.opsForSet().remove(RedisConstants.FOLLOWER_KEY + userId , followUserId.toString());
            }

        }
        return Result.ok();
    }

    /**
     * 是否关注
     * @param followUserId
     * @return
     */
    @Override
    public Result isFollow(Long followUserId) {
        // 1. 取出当前登录的用户id 作为关注者的id
        Long userId = UserHolder.getUser().getId();

        // 查询数据，是否存在
        Integer count = query()
                .eq("user_id" ,userId)
                .eq("follow_user_id",followUserId).count();

        if(count > 0){
            return Result.ok(Boolean.TRUE);
        }
        return Result.ok(Boolean.FALSE);
    }

    /**
     * 查询共同关注
     * @param id
     * @return
     */
    @Override
    public Result followCommons(Long id) {
        // 获取用户信息
        Long userId = UserHolder.getUser().getId();
        String key1 = RedisConstants.FOLLOWER_KEY + userId;
        String key2 = RedisConstants.FOLLOWER_KEY + id;

        // 2. 求两者关注列表的交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);

        if(intersect==null || intersect.isEmpty() ){
            // 3. 如果没有共同关注，则返回空集合
            return Result.ok(Collections.emptyList());
        }

        // 3. 解析id集合
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());

        // 4. 查询数据库
        List<UserDTO> userDTOs = userService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOs);
        }
}
